package com.example.camera;

import android.annotation.SuppressLint;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Build;

public class AutoFocusManager implements Camera.AutoFocusCallback {
	
	private Camera camera;
	private boolean focusing;
	
	private AutoFocusTask outStandingTask;
	
	public AutoFocusManager(Camera camera) {
		this.camera = camera;
		
		start();
	}

	@Override
	public void onAutoFocus(boolean success, Camera camera) {
		focusing = false;
		autoFocusAgainLater();
		
	}
	
	
	public void start() {
		camera.autoFocus(this);
		focusing = true;
	}
	
	@SuppressLint("NewApi")
	private void autoFocusAgainLater() {
		if(outStandingTask == null) {
			AutoFocusTask newTask = new AutoFocusTask();
			if(Build.VERSION.SDK_INT >= 11) {
				newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			} else {
				newTask.execute();
			}
			outStandingTask = newTask;
		}
	}
	
	
	public void stop() {
		cancelOutStandingTask();
		camera.cancelAutoFocus();
	}

	public void cancelOutStandingTask() {
		if(outStandingTask != null) {
			if(outStandingTask.getStatus() != AsyncTask.Status.FINISHED) {
				outStandingTask.cancel(true);
			}
			outStandingTask = null;
		}
	}
	
	
	private final class AutoFocusTask extends AsyncTask<Object, Object, Object> {

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			start();
			return null;
		}
		
	}
}
